/**
 * 
 */
package com.moyq5.permit.center.feign.server;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;

import com.moyq5.mvc.framework.jackson.result.StatusResult;
import com.moyq5.permit.center.core.ServiceOpenException;

/**
 * Controller 基类
 * 
 * @author Moyq5
 * @date 2016年9月19日
 */
public class BaseController {
	
	private static final Logger log = LoggerFactory.getLogger(BaseController.class);
	
	@InitBinder
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		CustomDateEditor editor = new CustomDateEditor(df, true);// true表示允许为空，false反之
		binder.registerCustomEditor(Date.class, editor);
	}

	@ExceptionHandler({ MethodArgumentNotValidException.class })
	@ResponseBody
	public StatusResult handleBindException(MethodArgumentNotValidException ex) {
		StatusResult jsonResult = new StatusResult();
		BindingResult br = ex.getBindingResult();
		jsonResult.setCode(br.getFieldError().getCode());
		jsonResult.setMessage(br.getFieldError().getDefaultMessage());
		return jsonResult;
	}

	@ExceptionHandler({ BindException.class })
	@ResponseBody
	public StatusResult handleBindException(BindException ex) {
		StatusResult result = new StatusResult();
		BindingResult br = ex.getBindingResult();
		result.setCode(br.getFieldError().getCode());
		result.setFailMessage(br.getFieldError().getDefaultMessage());
		return result;
	}
	
	@ExceptionHandler({ ServiceOpenException.class })
	@ResponseBody
	public StatusResult serviceOpenException(ServiceOpenException e) {
		StatusResult result = new StatusResult();
		result.setCode(e.getCode());
		result.setFailMessage(e.getMessage());
		return result;
	}
	
	@ExceptionHandler({ Exception.class })
	@ResponseBody
	public StatusResult serviceOpenException(Exception e) {
		log.error("系统异常：" + e.getMessage(), e);
		StatusResult result = new StatusResult();
		result.setCode("9999");
		result.setFailMessage(e.getMessage());
		return result;
	}
}
